//
//  OrderPostVC.swift
//  旅航ios
//
//  Created by tulip on 2021/5/7.
//

import UIKit
import SwiftyJSON

class OrderPostVC: UIViewController,UITableViewDelegate,UITableViewDataSource {
    
    @IBOutlet weak var agreenBtn: UIButton!
    var ticketPrice=0
    var fuPrice=50
    var bxData:JSON?
    var singleBaoxianPrice=0
    var mobile=""
    var contactName=""
    var idArr:Array<Int>=[]
    
    @IBOutlet weak var table: UITableView!
    
   
    var payTip:PayTipView!
    var payView:WX_ZhifuView!
    var fromCtiy:String!
    var toCity:String!
    var sendDic:Dictionary<String,Any>!
    var infoArr:[JSON]?
    var data:JSON!
    var passagerArr:Array<Dictionary<String,Any>>=[]
    var pNum=0
    @IBOutlet weak var bottomView: UIView!
    var headview:HangbanHeadview!
    
    @IBOutlet weak var mingxiBtn: UIButton!
    
    @IBOutlet weak var price: UILabel!
    var mingxi:MingXiBottom!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.view.backgroundColor=UIColor.init(hexString: "f7f7f7")
        headview =  HangbanHeadview.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: TopSpaceHeight))
       // headview.setAddress1(address1: "xx", address2: "xx")
        self.view.addSubview(headview)
        
        agreenBtn.setImage(UIImage(named: "支付方式-dot选中"), for: .selected)
        
//        table=UITableView.init(frame: CGRect(x: 0, y: TopSpaceHeight, width: SCREEN_WIDTH, height: bottomView.frame.origin.y-TopSpaceHeight))
//        self.view.addSubview(table)
        table.delegate=self
        table.dataSource=self
        table.separatorStyle = .none
        table.showsVerticalScrollIndicator=false
        table.estimatedRowHeight=220
        table.register(UINib(nibName: "OrderPostHeadCell", bundle: nil), forCellReuseIdentifier: "OrderPostHeadCell")
        table.register(UINib(nibName: "AddPassagerCell", bundle: nil), forCellReuseIdentifier: "AddPassagerCell")
        table.register(UINib(nibName: "InputContactCell", bundle: nil), forCellReuseIdentifier: "InputContactCell")
        table.register(UINib(nibName: "BaoxianCell", bundle: nil), forCellReuseIdentifier: "BaoxianCell")
        table.register(UINib(nibName: "BaoxiaoCell", bundle: nil), forCellReuseIdentifier: "BaoxiaoCell")
        table.reloadData()
        
        table.backgroundColor=UIColor.clear
        
        payTip=PayTipView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: ScreenHight))
        payView=WX_ZhifuView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: ScreenHight))
        
        if price.text == "---"{
            mingxiBtn.isHidden=true
        }
        
        Network.request(.baoxian) { JSON in
            self.bxData=JSON["data"]
            self.table.reloadData()
        } failure: { err in
            
        }

        
        
        Network.request(.searchBK(sendDic)) { (JSON) in
            let code=JSON["code"].int
            if code == 0 {
                self.navigationController?.popViewController(animated: true)
                YProgressHUD.showToast(JSON["msg"].string)
            }else{
            
            self.infoArr = JSON["data"]["flightInfo"].array
            self.data=JSON["data"]
                
//                print("******\(JSON["data"]["flightInfo"][0]["arf"])  \(self.infoArr?[0]["tof"])")
                self.fuPrice = Int((self.infoArr?[0]["arf"].string)!)! + Int((self.infoArr?[0]["tof"].string)!)!
            self.table.reloadData()
                let city1=self.infoArr?[0]["dptCity"].string ?? ""
                let city2=self.infoArr?[0]["arrCity"].string ?? ""
            self.headview.setAddress1(address1: city1, address2: city2)
                let price=JSON["data"]["extInfo"]["barePrice"].string
                self.ticketPrice=Int(Float(JSON["data"]["extInfo"]["barePrice"].string ?? "0") ?? 0)
                print(self.ticketPrice,"----",price)
                
            }
        } failure: { (err) in
            
        }

        NotificationCenter.default.addObserver(self, selector: #selector(addPassagers), name: NSNotification.Name(rawValue: "addPassagersNotify"), object: nil)
        
    }
    

    func numberOfSections(in tableView: UITableView) -> Int {
        5
    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell:OrderPostHeadCell=tableView.dequeueReusableCell(withIdentifier: "OrderPostHeadCell", for: indexPath) as! OrderPostHeadCell
            
            if (infoArr?.count ?? 0) > 0{
                cell.setInfo(arr: infoArr ?? [])
                cell.infoArr=infoArr ?? []
            }
            
            return cell
        }
        if indexPath.section == 1 {
            let cell:AddPassagerCell=tableView.dequeueReusableCell(withIdentifier: "AddPassagerCell", for: indexPath) as! AddPassagerCell
            cell.propPassagerIDArr={[weak self](arr,dicArr) in
                self?.idArr=arr
                print(self?.idArr)
                self?.passagerArr=dicArr
                self?.table.reloadData()
                self?.countPrice()
            }
            
            return cell
        }
        if indexPath.section == 2 {
            let cell:InputContactCell=tableView.dequeueReusableCell(withIdentifier: "InputContactCell", for: indexPath) as! InputContactCell
            cell.propPhoneNum={[weak self](str) in
                self?.mobile=str
            }
            cell.propNameStr={[weak self](str) in
                self?.contactName=str
            }
            if passagerArr.count > 0{
                
                cell.name.text=passagerArr[0]["name"] as? String
                cell.phone.text=passagerArr[0]["phone"] as? String
                self.contactName=cell.name.text ?? ""
                self.mobile=cell.phone.text ?? ""
            }
            
            return cell
        }
        if indexPath.section == 3 {
            let cell:BaoxianCell=tableView.dequeueReusableCell(withIdentifier: "BaoxianCell", for: indexPath) as! BaoxianCell
            let name=bxData?["name"].string ?? ""
            cell.title.setTitle(name, for: .normal)
            let price=bxData?["price"].string ?? ""
            cell.btn.setTitle(price, for: .normal)
            self.singleBaoxianPrice=Int(Float(price) ?? 0)
            cell.propChoose={[weak self](bool) in
                if bool {
                    let price=self?.bxData?["price"].string ?? ""
                    self?.singleBaoxianPrice=Int(Float(price) ?? 0)
                    if self?.ticketPrice != 0 {
                        self?.countPrice()
                    }
                }else{
                    self?.singleBaoxianPrice=0
                    if self?.ticketPrice != 0 {
                        self?.countPrice()
                    }
                }
            }
            return cell
        }
        let cell:BaoxiaoCell=tableView.dequeueReusableCell(withIdentifier: "BaoxiaoCell", for: indexPath) as! BaoxiaoCell
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section==0{
            return 105
        }
        if indexPath.section==1{
            
            Network.request(.getPassager(parameters: ["token" : TOKEN])) { (JSON) in
                let arr =  JSON["data"].array ?? []
                self.pNum=arr.count
            } failure: { (err) in
                
            }
            return CGFloat(120+80*pNum)
        }
        if indexPath.section==2{
            return 130
        }
        if indexPath.section==3{
            return UITableView.automaticDimension
        }
        return UITableView.automaticDimension
    }
    
    func countPrice(){
        let num=idArr.count
        if num > 0 {
            mingxiBtn.isHidden=false
            let t_price=num*(singleBaoxianPrice+ticketPrice+fuPrice)
            price.text=String(t_price)
        }else{
            price.text="---"
            mingxiBtn.isHidden=true
        }
    }

    @IBAction func postOrder(_ sender: Any) {
     
        if idArr.isEmpty{
            YProgressHUD.showToast("请添加乘机人")
        }
        else if contactName == ""{
            YProgressHUD.showToast("请输入联系人姓名")
        }
       else if mobile == "" {
            YProgressHUD.showToast("请输入联系人号码")
       }else if agreenBtn.isSelected == false {
           YProgressHUD.showToast("请阅读并同意相关协议")
       }

       else{
        let departDate=infoArr?[0]["dptDate"].string ?? ""
        let departCityCode=infoArr?[0]["dpt"].string ?? ""
        let arriveCityCode=infoArr?[0]["arr"].string ?? ""
        let flightNo=infoArr?[0]["flightNum"].string ??  ""
        let dic=["departDate":departDate,
                 "departCityCode": departCityCode,
                 "arriveCityCode":arriveCityCode,
                 "flightNo":flightNo,
                 "ticketPrice":sendDic["ticketPrice"] ?? "",
                 "barePrice":sendDic["barePrice"] ?? "",
                 "productId":sendDic["productId"] ?? "",
                 "cabin":sendDic["cabin"] ?? "",
                 "orderLink":contactName,
                 "mobile":mobile,
                 "passengers":idArr,
                 "invoiceType":0,
                 "xcd":0,
                 "bx":0,
                 "flightDelayBx":0,
                 "tuipiaoBx":0,
                 "receiverTitle":"",
                 "receiverType":"",
                 "taxpayerId":"",
                 "sjr":"",
                 "sjrPhone":"",
                 "address":""]
        
        Network.request(.airTicketOrder(dic)) { (JSON) in
            YProgressHUD.showToast(JSON["msg"].string)
            print(JSON["data"]["order_id"].string)
            self.payTip.tkData=self.infoArr?[0]
            self.payTip.pgData=self.passagerArr
            self.payTip.setUI()
            self.view.addSubview(self.payTip)
            self.payView.orderId="\(JSON["data"]["order_id"].string ?? "")"
            DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
                self.payTip.removeFromSuperview()
                self.view.addSubview(self.payView)

            }
        } failure: { (err) in
            
        }

        
       }
       
    }
    
    @IBAction func tickeDetail(_   sender: UIButton) {  //价格明细
        if !sender.isSelected {
            sender.isSelected = true
            if mingxi == nil {
                mingxi=MingXiBottom.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: bottomView.frame.origin.y))
            }
            mingxi.setPrice(tk: ticketPrice, fu: fuPrice, bx: singleBaoxianPrice, num: idArr.count)
            mingxi.propStatus={
                sender.isSelected=false
            }
            self.view.addSubview(mingxi)
        }else{
            mingxi.removeFromSuperview()
            sender.isSelected=false
        }
        
        
    }
    
    
    @objc func addPassagers(sender:Notification){
        let arr:Array<PassagerCell> =  sender.object as! Array<PassagerCell>
        for a in arr{
            passagerArr.append(a.mdic)
        }
        table.reloadData()
        
    }
    
    
    @IBAction func agreen(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
    }
    
    
    @IBAction func readAgreement(_ sender: Any) {
//        let vc=AgreementListVC.init()
//        self.navigationController?.pushViewController(vc, animated: true)
        
        Network.request(.orderNotice) { JSON in
            self.data=JSON["data"]
            self.table.reloadData()
            
            
            let vc=AgreementVC.init()
            vc.titleStr = JSON["data"]["name"].string
            vc.htmlStr = JSON["data"]["content"].string
           
            self.navigationController?.pushViewController(vc, animated: true)
            
        
        } failure: { err in
            
        }
        
        
        
        
        
    }
    
}
